package com.example.administrator.liveapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.base.BaseRVAdapter;
import com.example.administrator.liveapp.base.BaseViewHolder;
import com.example.administrator.liveapp.utils.SearchSQL;

import junit.framework.Test;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 首页跳转全局搜索activity
 */

public class SearchActivity extends Activity implements View.OnClickListener{

    //@Bind(R.id.edit)
    EditText edit;
    // @Bind(R.id.clear)
    TextView clear;
    // @Bind(R.id.line_clear)
    LinearLayout line_clear;
    // @Bind(R.id.flow)
//    FlowLayout flow;
//     @Bind(R.id.recycler)
    RecyclerView history;
    private SearchSQL helper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
    }

    protected void initView() {
        edit = (EditText) findViewById(R.id.edit);
        clear = (TextView) findViewById(R.id.clear);
        line_clear = (LinearLayout) findViewById(R.id.line_clear);
        findViewById(R.id.search).setOnClickListener(this);
        findViewById(R.id.clear).setOnClickListener(this);
//        flow = (FlowLayout) findViewById(R.id.flow);
        history = (RecyclerView) findViewById(R.id.recycler);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//阻止软键盘弹出时底部菜单上移
        helper = new SearchSQL(this);
        strings = queryData();
        if (strings.size() != 0) line_clear.setVisibility(View.VISIBLE);
        initEdit();
//        initFlow();
        initHistory();
    }

    private void initEdit() {
        edit.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String searchStr = edit.getText().toString();
                    if (searchStr.equals("")) {
                        Toast.makeText(SearchActivity.this, "请输入搜索内容!", Toast.LENGTH_SHORT).show();
                    } else {
//                        Toast.makeText(SearchActivity.this, "" + searchStr, Toast.LENGTH_SHORT).show();
                        // 先隐藏键盘
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                                getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        addSearch(searchStr);

                    }
                    return true;
                }
                return false;
            }
        });

    }

    private List<String> strings;

    private void initHistory() {
        history.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
        BaseRVAdapter baseRVAdapter = new BaseRVAdapter(this, strings) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_search_history;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                holder.setTextView(R.id.text, strings.get(position));
                holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteData(strings.get(position));
                        strings.remove(position);
                        if (strings.size() == 0) line_clear.setVisibility(View.GONE);
                        notifyDataSetChanged();
                    }
                });
                addItemClickListener(new OnItemClickListener() {
                    @Override
                    public void itemSelect(int position) {
                        edit.setText(strings.get(position));
                    }
                });
            }
        };
        history.setAdapter(baseRVAdapter);
    }


    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, SearchActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);
    }

//    private void initFlow() {
//        // 设置条目的水平间距
//        flow.setChildViewHorizontalPadding(DensityUtil.dip2px(15f));
//        // 设置每行的垂直间距
//        flow.setChildViewVerticalPadding(DensityUtil.dip2px(10f));
//        final List<String> test = new ArrayList<>();
//        test.add("asdasdsa");
//        test.add("阿贾克斯封口机");
//        test.add("阿贾克机");
//        test.add("gghh");
//        test.add("asdasdsa");
//        test.add("afa");
//        test.add("你好");
//        test.add("封口机");
//
//
//        for (int i = 0; i < test.size(); i++) {
//            addTextView("" + test.get(i));
//        }
//
//    }

    private void addTextView(final String str) {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(str);
        textView.setTextSize(12);
        textView.setPadding(DensityUtil.dip2px(12f),
                DensityUtil.dip2px(7f),
                DensityUtil.dip2px(12f)
                , DensityUtil.dip2px(7f));

        textView.setBackgroundResource(R.drawable.b_search_bg);
        textView.setTextColor(ContextCompat.getColor(this, R.color.black));

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addSearch(str);
            }
        });
//        flow.addView(textView);
    }

// R.id.switchs//换一批
//    @OnClick({R.id.back, R.id.search, R.id.clear})
//    public void click(View view) {
//        switch (view.getId()) {
//            case R.id.back:
//            case R.id.search:
//                Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
//                finish();
//                overridePendingTransition(R.anim.fade_in,
//                        R.anim.fade_out);
//                break;
////            case R.id.switchs:
//////                showShortToast("换一批");
////                break;
//            case R.id.clear:
//                Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
//                deleteData();
//                strings.clear();
//                line_clear.setVisibility(View.GONE);
//                history.setVisibility(View.GONE);
//                break;
//        }
//
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
            case R.id.search:
                finish();
                overridePendingTransition(R.anim.fade_in,
                        R.anim.fade_out);
                break;
//            case R.id.switchs:
////                showShortToast("换一批");
//                break;
            case R.id.clear:
                deleteData();
                strings.clear();
                line_clear.setVisibility(View.GONE);
                history.setVisibility(View.GONE);
                break;
        }
    }

    public void addSearch(String str) {
        db = helper.getWritableDatabase();
        int size = queryData().size();
        if (!hasData(str)) {
            if (size >= 5)
                db.execSQL(" delete from records where   id= (select id from records   order by  id  limit  0,1 )");
        } else {
            if (size != 0)
                db.execSQL("delete from records where   name= '" + str + "'");
        }
        db.execSQL("insert into records(name) values('" + str + "')");
        db.close();
        strings = queryData();
        line_clear.setVisibility(View.VISIBLE);
        history.setVisibility(View.VISIBLE);
        initHistory();
        Intent intent = new Intent(SearchActivity.this,SearchPage.class);
        intent.putExtra("seaContent",str);
        startActivity(intent);
        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
    }

    private void deleteData(String s) {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records where   name= '" + s + "'");
    }

    /**
     * 查询所有数据
     */
    private List<String> queryData() {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select  name from records ", null);
        List<String> search = new ArrayList<>();
        search.clear();
        while (cursor.moveToNext()) {
            search.add(cursor.getString(cursor.getColumnIndex("name")));
        }
        //  Log.e("size", search.size() + "");

        return search;
    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select  name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

}
